<template>
  <div class="inventory">
    <el-button plain type="single-number" @click="showDialog()">
      {{ btnText }}
    </el-button>
    <el-dialog
      width="990px"
      :title="dialogTitle"
      :visible.sync="showDialogVisible"
      custom-class="revenue-code-number"
    >
      <div class="el-dialog__body-bodys">
        <div class="container">
          <div class="header">已选择({{ inventoryTableData2.length }}个)</div>
          <div class="ccui-multifunctional-table-wrapper">
            <el-table
              :data="inventoryTableData2"
              ref="multipleTable2"
              height="200"
              border
              :fit="true"
            >
              <el-table-column label="序号" width="45" fixed>
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(table, index) in tableHeadOptions"
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :min-width="table.width"
                :prop="table.prop"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :filters="table.filters"
                :formatter="table.formatter"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="操作" width="50px">
                <template slot-scope="{ row, $index }">
                  <el-button
                    size="mini"
                    type="text"
                    @click="inventoryDeleteTable(row, $index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="container">
          <el-search
            :formProp="inventoryForm"
            @search="inventorySearch"
            @change="inventoryChange"
            width="400px"
            placement="bottom-start"
            class="ccui-highsearch no-print"
          >
            <template slot="search">
              <template v-for="(item, index) in searchInputArr">
                <el-date-picker
                  v-if="item.type === 'daterange'"
                  :key="index"
                  v-model="inventoryForm[item.value]"
                  value-format="yyyy-MM-dd"
                  :searchLabel="item.label"
                  :clearable="false"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
                <el-date-picker
                  v-else-if="item.type === 'date'"
                  :key="index"
                  v-model="inventoryForm[item.value]"
                  value-format="yyyy-MM-dd"
                  :searchLabel="item.label"
                  :clearable="false"
                  type="date"
                  placeholder="选择日期"
                />
                <el-select
                  v-else-if="item.type === 'select'"
                  :key="index"
                  v-model="inventoryForm[item.value]"
                  :searchLabel="item.label"
                  :placeholder="`请选择${item.label}`"
                >
                  <el-option
                    v-for="item in item.selectData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-input
                  v-else
                  :key="index"
                  v-model.trim="inventoryForm[item.value]"
                  clearable
                  :searchLabel="item.label"
                  :placeholder="`请输入${item.label}模糊查询`"
                />
              </template>
            </template>
            <template v-for="(item, index) in searchInputArr">
              <el-date-picker
                v-if="item.type === 'daterange'"
                :key="index"
                v-model="inventoryForm[item.value]"
                value-format="yyyy-MM-dd"
                :searchLabel="item.label"
                :clearable="false"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :slot="`searchItem${index + 1}`"
              />
              <el-date-picker
                v-else-if="item.type === 'date'"
                :key="index"
                v-model="inventoryForm[item.value]"
                value-format="yyyy-MM-dd"
                :searchLabel="item.label"
                :clearable="false"
                type="date"
                placeholder="选择日期"
                :slot="`searchItem${index + 1}`"
              />
              <el-select
                v-else-if="item.type === 'select'"
                :key="index"
                v-model="inventoryForm[item.value]"
                :searchLabel="item.label"
                :placeholder="`请选择${item.label}`"
                :slot="`searchItem${index + 1}`"
              >
                <el-option
                  v-for="item in item.selectData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-input
                v-else
                :key="index"
                v-model.trim="inventoryForm[item.value]"
                clearable
                :searchLabel="item.label"
                :placeholder="`请输入${item.label}模糊查询`"
                :slot="`searchItem${index + 1}`"
              />
            </template>
          </el-search>
          <!-- 搜索条件开始 -->
          <!-- <div>
            <el-form
              :model="inventoryForm"
              ref="inventoryForm"
              label-width="94px"
              class="ccui-form"
              inline
            >
              <el-form-item
                v-for="(item, index) in searchInputArr"
                :key="index"
                :label="`${item.label}：`"
                :prop="item.value"
              >
                <el-date-picker
                  v-if="item.type === 'date'"
                  v-model="inventoryForm[item.value]"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
                <el-select
                  v-else-if="item.type === 'select'"
                  v-model="inventoryForm[item.value]"
                  :placeholder="`请选择${item.label}`"
                >
                  <el-option
                    v-for="item in item.selectData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-input
                  v-else
                  v-model.trim="inventoryForm[item.value]"
                  clearable
                  :searchLabel="item.label"
                  :placeholder="`请输入${item.label}模糊查询`"
                />
              </el-form-item>
            </el-form>

            <div class="search-btn">
              <el-button type="primary" size="mini" @click="inventorySearch"
                >搜索</el-button
              >
              <el-button size="mini" @click="inventoryReset">重置</el-button>
            </div>
          </div> -->
          <!-- 搜索条件结束 -->
          <div class="ccui-multifunctional-table-wrapper">
            <el-table
              :data="inventoryTableDatas"
              height="200"
              @select="inventorySelectTable"
              @select-all="inventorySelectTableAll"
              ref="inventoryMultipleTable"
              border
              :fit="true"
            >
              <el-table-column width="35" type="selection" />

              <el-table-column label="序号" width="45" align="center" fixed>
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(table, index) in tableHeadOptions"
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :min-width="table.width"
                :prop="table.prop"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :filters="table.filters"
                :formatter="table.formatter"
                :show-overflow-tooltip="true"
              />
            </el-table>
          </div>
          <div class="table-footer" style="height: 35px">
            <div class="ccui-table-footer">
              <div id="ccui-paging">
                <el-pagination
                  :total="inventoryTotal"
                  :page-size="inventoryPageSize"
                  :current-page="inventoryPageNoCode"
                  prev-text="< 上一页"
                  next-text="下一页 >"
                  background
                  layout=" prev, pager, next, jumper"
                  popper-class="ccui-paging-page-size-popper"
                  @current-change="inventoryHandleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          size="mini"
          type="default-mini"
          @click="showDialogVisible = false"
          >取 消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="inventoryConfirm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
// , uniqWith, isEqual
import { uniqueByJson } from "@/basa/utils";
import { loadingParams } from "@/basa/utils/public";
export default {
  name: "dialogMultiSelectTableTow",
  props: {
    // 按钮文字
    btnText: {
      type: String,
      default: "选择",
    },
    // 弹窗标题
    dialogTitle: {
      type: String,
      default: "",
    },
    // 错误提示
    errorMessage: {
      type: String,
      default: "",
    },
    // 搜索条件
    searchInputArr: {
      type: Array,
      default: () => [],
    },
    // 表格的表头
    tableHeadOptions: {
      type: Array,
      default: () => [],
    },
    storageFormTolal: {
      type: Object,
      default: () => {},
    },
    // 通过页面传进来的方法获取数据
    getTableList: {
      type: Function,
      default: Function,
    },
    // 可选择的参数
    optionalParams: {
      type: Object,
      default: () => {},
    },
    // 回显已选中的数据
    selectTableList: {
      type: Array,
      default: () => [],
    },
    // 条件判断显示
    isShow: {
      type: Boolean,
      default: false,
    },
    // 数组当前行下标
    rowIndex: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      showDialogVisible: false,
      inventoryForm: {},
      inventoryTableDatas: [],
      inventoryTotal: 0,
      inventoryPageNoCode: 1,
      inventoryPageSize: 10,
      inventoryTableData2: [],
      beforeSelectData: [],
      selectTableListTow: [], // 回显数据拷贝
      selectList: [],
      contractCode: null,
      storageType: null,
    };
  },
  methods: {
    showDialog() {
      if (this.isShow) {
        if(this.optionalParams && this.optionalParams.reportInOrgId){
          this.showDialogVisible = true;
          if (this.storageFormTolal) {
            this.contractCode = this.storageFormTolal.contractCode;
            this.storageType =
              this.storageFormTolal.storageType == "正式入库" || this.storageFormTolal.storageType == 1 ? 1 : 2;
          }
          this.selectTableListTow = JSON.parse(
            JSON.stringify(this.selectTableList)
          );
          this.inventoryGetMcConcBill();
        }else{
          this.$message({
          message: "请先选择填报单位",
          type: "error",
          showClose: true,
          ccuiCustom: true
        });
        }
      } else {
        this.$showErrorMessage(this.errorMessage);
      }
    },
    inventoryGetMcConcBill() {
      // 过滤时间参数
      const tempForm = cloneDeep(this.inventoryForm);
      for (const key in tempForm) {
        if (Object.hasOwnProperty.call(tempForm, key)) {
          const ele = tempForm[key];
          const { type } = this.searchInputArr.find((_) => _.value === key);
          switch (type) {
            // 需要加开始结束时间的
            case "daterange":
              tempForm[`${key}Start`] = ele[0];
              tempForm[`${key}End`] = ele[1];
              delete tempForm[key];
              break;

            default:
              break;
          }
        }
      }

      // 合并参数
      let params = {
        pageNo: this.inventoryPageNoCode,
        pageSize: this.inventoryPageSize,
        contractCode: this.contractCode,
        storageType: this.storageType,
        ...tempForm,
        ...this.optionalParams,
        ...loadingParams,
      };

      // 请求接口
      this.getTableList(params).then((res) => {
        if (
          this.selectTableListTow.length &&
          this.selectTableListTow[0].storageCode === "当期"
        ) {
          this.selectList.push(this.selectTableListTow[0]);
          this.inventoryTableData2 = this.selectTableListTow;
        } else {
          this.inventoryTableData2 = this.selectTableListTow;
        }
        this.inventoryTableDatas = res.data.data.rows;
        this.inventoryTableDatas.forEach(item => {
          item.storageCount = (+item.storageCount).toFixed(3);
        })
        this.inventoryTotal = res.data.data.recordsTotal;
        this.inventoryPageNoCode = res.data.data.pageNo;

        const storageCodeSetObj = new Set(
          this.inventoryTableData2.map((_) => _.storageCode)
        );
        this.$nextTick(() => {
          this.$refs.inventoryMultipleTable.doLayout();
          this.$refs.multipleTable2.doLayout();
          this.inventoryTableDatas.map((n) => {
            if (storageCodeSetObj.has(n.storageCode)) {
              this.$refs.inventoryMultipleTable.toggleRowSelection(n, true);
            }
          });
        });
      });
    },
    inventoryHandleCurrentChange(val) {
      this.inventoryPageNoCode = val;
      this.inventoryGetMcConcBill();
    },
    inventorySearch(searchData) {
      this.inventoryPageNoCode = 1;
      this.inventoryGetMcConcBill();
    },
    inventoryChange(index, key, value) {
      const formDataKeys = Object.keys(this.inventoryForm);
      formDataKeys.map((_) => {
        if (_ !== key) this.inventoryForm[_] = "";
      });
    },
    // 单选
    inventorySelectTable(selection, row) {
      //console.log(selection);
      // storageCode  每条数据的唯一 id
      // const { storageCode } = row;
      this.inventoryTableData2 = [...this.selectTableListTow, ...selection];
      // 去重
      this.inventoryTableData2 = uniqueByJson(
        this.inventoryTableData2,
        "storageCode"
      );
      if (this.inventoryTableData2.length <= 0) {
        this.inventoryGetMcConcBill();
      }
      this.selectTableListTow = this.inventoryTableData2;
      this.beforeSelectData = selection.map((n) => n.storageCode);
    },
    // 全选
    inventorySelectTableAll(selection) {
      this.inventoryTableData2 = [...this.selectTableListTow, ...selection];
      // 去重
      this.inventoryTableData2 = uniqueByJson(
        this.inventoryTableData2,
        "storageCode"
      );
      this.selectTableListTow = this.inventoryTableData2;
      this.beforeSelectData = selection.map((n) => n.storageCode);
    },
    // 删除
    inventoryDeleteTable(row, index) {
      if (row.storageCode == "当期") {
        this.selectList = [];
      }
      const filterData = this.inventoryTableData2.filter(
        (item) => item.storageCode !== row.storageCode
      );
      this.inventoryTableData2 = filterData;
      this.selectTableListTow = filterData;
      this.beforeSelectData = filterData.map((n) => n.storageCode);
      this.inventoryGetMcConcBill();
    },
    inventoryConfirm() {
      this.showDialogVisible = false;
      this.$emit("confirm", this.inventoryTableData2, this.rowIndex);
      this.resetParams();
    },
    // 重置表单
    inventoryReset() {
      this.$refs.inventoryForm.resetFields();
    },
    resetParams() {
      this.inventoryPageNoCode = 1;
      this.inventoryPageSize = 10;
      this.inventoryForm = {};
      this.inventoryTableDatas = [];
      this.inventoryTableData2 = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.inventory {
  display: inline-block;
  & + .inventory {
    margin-left: 10px;
  }
  /deep/ .el-dialog__header {
    // display: flex;
    // align-items: center;
  }
  /deep/ .el-dialog__title {
    display: inline-block;
    height: 20px;
    line-height: 20px !important;
  }
  /deep/ .revenue-code-number {
    .el-dialog__body {
      width: auto;
      height: auto;
      .ccui-form {
        margin-top: 5px;
      }
    }
  }
  /deep/ .revenue-code-number .el-dialog__body .el-dialog__body-bodys {
    .bodys-right {
      padding: 0;
      width: 400px;
    }
  }
  /deep/.el-search .el-searchs {
    float: none !important;
  }
  /deep/.el-searchs-box {
    // width: auto !important;
    margin: 0 auto;
  }
  .container {
    border: 1px solid #f1f1f1;
    padding: 10px 20px;
    .header {
      margin-bottom: 10px;
    }
    .table-footer {
      padding: 10px 0;
    }
    .ccui-statistics-card {
      padding: 0;
    }
  }
  /deep/.el-button--text {
    font-size: 13px;
  }
  /deep/.el-input {
    width: 192px;
  }
  .search-btn {
    text-align: center;
    padding: 0 0 20px 0;
  }
  // 搜索条件 启动
  /deep/ .el-form.el-searchs-bottom-form {
    .el-row {
      width: 100%;
    }
    .el-date-editor {
      width: 192px;
      .el-range-input {
        width: 50%;
      }
      .el-range-separator {
        padding: 0 10px 0 5px;
        font-size: 13px;
      }
      .el-range__close-icon,
      .el-range__icon {
        display: none;
      }
    }
  }
  /deep/ .el-dialog__body .el-form .el-form-item:last-child {
    margin-bottom: 16px;
  }
  // 搜索条件 结束
  /deep/ .ccui-multifunctional-table-wrapper .el-table {
    .el-table__body-wrapper {
      z-index: 2;
    }
    td,
    th.is-leaf {
      border-right: 1px solid #edf2fc;
    }
    // 固定行的高
    .el-table__fixed {
      height: 100% !important;
    }
    td.is-hidden > *,
    th.is-hidden > * {
      visibility: inherit;
    }
  }
}

/deep/ .el-table {
  /deep/ th {
    padding: 0;
    height: 36px;
    line-height: 36px;
  }

  .el-table__body {
    .cell {
      height: 36px;
      line-height: 36px;
    }
  }
}
</style>
